package com.aiyan.edu.service.order.service;

import com.aiyan.edu.framework.domain.task.Task;
import com.aiyan.edu.framework.domain.task.TaskHis;
import com.aiyan.edu.service.order.dao.TaskHisRepository;
import com.aiyan.edu.service.order.dao.TaskRepository;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author: zqzhou
 * @create: 2019/11/24 16:37
 **/
@Service
public class TaskService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    TaskRepository taskRepository;

    @Autowired
    TaskHisRepository taskHisRepository;

    /**
     * 查询前n条任务
     *
     * @param updateTime
     * @param size
     * @return
     */
    public List<Task> findTaskList(Date updateTime, int size) {
        Page<Task> taskPage = this.taskRepository.findByUpdateTimeBefore(new PageRequest(0, size), updateTime);
        return taskPage.getContent();
    }

    /**
     * 发送消息
     *
     * @param task
     */
    public void publish(Task task) {
        String exchange = task.getMqExchange();
        String routingKey = task.getMqRoutingkey();
        Optional<Task> byId = taskRepository.findById(task.getId());

        if (byId.isPresent()) {
            this.rabbitTemplate.convertAndSend(exchange, routingKey, task);

            // 更新任务时间
            Task taskToSave = byId.get();
            this.taskRepository.save(taskToSave);
        }
    }

    /**
     * 获取任务，通过事务来控制多个节点获取任务的先后
     */
    @Transactional
    public int getTask(String id, int version) {
        //通过乐观锁的方式来更新数据表，如果结果大于0说明取到任务
        int count = this.taskRepository.updateTaskVersion(id, version);
        return count;
    }

    /**
     * 完成任务
     *
     * @param taskId
     */
    @Transactional
    public void finishTask(String taskId) {
        Optional<Task> optionalTask = this.taskRepository.findById(taskId);
        if (optionalTask.isPresent()) {
            //当前任务
            Task xcTask = optionalTask.get();
            //历史任务
            TaskHis xcTaskHis = new TaskHis();
            BeanUtils.copyProperties(xcTask, xcTaskHis);
            this.taskHisRepository.save(xcTaskHis);
            this.taskRepository.delete(xcTask);
        }
    }
}
